<template>
  <el-select ref="refSelect" :value="valueTitle" :clearable="clearable" @clear="clearHandle">
    <el-input
      v-show="showFilter"
      v-model="filterText"
      :placeholder="placeholder"
      class="selectInput"
    />
    <el-option :value="valueTitle" :label="valueTitle" class="options">
      <el-tree
        id="tree-option"
        ref="refTree"
        :accordion="accordion"
        :data="options"
        :props="objProps"
        :node-key="objProps.value"
        :default-expanded-keys="defaultExpandedKey"
        :filter-node-method="filterNode"
        @node-click="handleNodeClick"
      />
    </el-option>
  </el-select>
</template>

<script>
import { defineComponent, ref, onMounted, watch, nextTick } from 'vue'
export default defineComponent({
  name: 'TreeSelectCom',
  props: {
    // 配置项
    objProps: {
      type: Object,
      default: () => {
        return {
          value: 'id',
          label: 'title',
          children: 'children',
        }
      },
    },
    // 选项列表数据(树形结构的对象数组)
    options: {
      type: Array,
      default: () => {
        return []
      },
    },
    // 从父组件传过来的默认初始值
    value: { type: Number, default: 1 },
    // 可清空选项
    clearable: { type: Boolean, default: true },
    // 自动收起
    accordion: { type: Boolean, default: false },
    showFilter: { type: Boolean, default: true },
    placeholder: {
      type: String,
      default: () => {
        return '检索关键字'
      },
    },
  },
  emit: ['get-value'],
  setup(props, { emit }) {
    const filterText = ref('')
    const valueId = ref(1)
    const valueTitle = ref('')
    const defaultExpandedKey = ref([])
    const selectTree = ref(null)
    const refTree = ref(null)

    // const changeMessage = async (newMessage) => {
    //   nextTick(() => {})
    // }

    // 初始化值
    const initHandle = () => {
      if (props.value) {
        nextTick(() => {
          // 设置默认选中
          refTree.value.setCurrentKey(props.value)
          // 设置默认展开
          defaultExpandedKey.value = [props.value]
          const node = refTree.value.getNode(props.value)
          if (node != null) {
            valueTitle.value = node.data[props.objProps.label]
          }
        })
      } else {
        valueTitle.value = ''
      }
      initScroll()
    }
    // 初始化滚动条
    const initScroll = () => {
      nextTick(() => {
        const scrollWrap = document.querySelectorAll('.el-scrollbar .el-select-dropdown__wrap')[0]
        const scrollBar = document.querySelectorAll('.el-scrollbar .el-scrollbar__bar')
        scrollWrap.style.cssText = 'margin: 0px; max-height: none; overflow: hidden;'
        scrollBar.forEach((ele) => (ele.style.width = 0))
      })
    }

    // 点击tree的节点时，表示切换选项
    const handleNodeClick = (node) => {
      valueTitle.value = node[props.objProps.label]
      valueId.value = node[props.objProps.value]
      emit('getValue', valueId.value)
      defaultExpandedKey.value = []
    }

    // 清除选中
    const clearHandle = () => {
      valueId.value = null
      valueTitle.value = ''
      defaultExpandedKey.value = []
      clearSelected()
      emit('getValue', null)
    }
    // 清空选中样式
    const clearSelected = () => {
      const allNode = document.querySelectorAll('#tree-option .el-tree-node')
      allNode.forEach((element) => element.classList.remove('is-current'))
    }
    const filterNode = (val, data) => {
      if (!val) return true
      return data.title.indexOf(val) !== -1
    }

    onMounted(() => {
      initHandle()
    })

    watch(
      () => props.value,
      (newVal, oldVal) => {
        console.log('new', newVal)
        console.log('old', oldVal)
        valueId.value = newVal
        initHandle()
      },

      () => props.options,
      (newVal, oldVal) => {
        console.log('new', newVal)
        console.log('old', oldVal)
        valueId.value = newVal
        initHandle()
      },

      () => filterText,
      (val) => {
        selectTree.value.filter(val)
      }
    )

    return {
      filterText,
      valueId,
      valueTitle,
      defaultExpandedKey,
      selectTree,
      refTree,
      initHandle,
      initScroll,
      handleNodeClick,
      clearHandle,
      clearSelected,
      filterNode,
    }
  },
})
</script>

<style scoped>
.el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
  height: auto;
  max-height: 274px;
  padding: 0;
  overflow: hidden;
  overflow-y: auto;
}
.el-select-dropdown__item.selected {
  font-weight: normal;
}
ul li >>> .el-tree .el-tree-node__content {
  height: auto;
  padding: 0 20px;
}
.el-tree-node__label {
  font-weight: normal;
}
.el-tree >>> .is-current .el-tree-node__label {
  color: #409eff;
  font-weight: 700;
}
.el-tree >>> .is-current .el-tree-node__children .el-tree-node__label {
  color: #606266;
  font-weight: normal;
}
.selectInput {
  padding: 0 5px;
  box-sizing: border-box;
}
</style>
